//
//  SimpleScheduleViewController.m
//  GolfFriend
//
//  Created by vescky on 13-11-30.
//  Copyright (c) 2013年 vescky.org. All rights reserved.
//

#import "SimpleScheduleViewController.h"
#import "ScheduleDAO.h"
#import "ScheduleContentVo.h"
#import "SimpleScheduleCell.h"
#import "DateUtility.h"
#import "UserSession.h"

@interface SimpleScheduleViewController () {
    ScheduleDAO *sDao;
    NSMutableArray *sContentArray;
    SimpleScheduleCell *sampleCell;
}

@end

@implementation SimpleScheduleViewController
@synthesize delegate,userId;

#pragma mark - lifeCycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Public
- (IBAction)btnAddSchedule:(id)sender {
    if ([self.delegate respondsToSelector:@selector(btnAddDidSelected)]) {
        [self.delegate btnAddDidSelected];
    }
    NSLog(@"btnAddDidSelected");
}

- (void)refreshSchedule {
    [self initView];
    [tbSchedule reloadData];
}

- (bool)saveScheduleWith:(NSDate*)_date content:(NSString*)_content {
    if (!_date || !_content) {
        return NO;
    }
    ScheduleContentVo *scVo = [[ScheduleContentVo alloc] init];
    scVo.userId = userId;
    scVo.dateString = getStringFromDate(@"MM月dd", _date);
    scVo.timeString = getStringFromDate(@"HH:mm", _date);
    scVo.content = _content;
    
    NSString *dateNowString = getStringFromDate(@"yyyy-MM-dd", [NSDate date]);
    NSString *_dateString = getStringFromDate(@"yyyy-MM-dd", _date);
    NSDate *dateNow1 = getDateFromString(@"yyyy-MM-dd", dateNowString);
    NSDate *_date1 = getDateFromString(@"yyyy-MM-dd", _dateString);
    if ([dateNow1 isEqualToDate:_date1]) {
        scVo.status = @"0";
    }
    else if ([dateNow1 isEqualToDate:[dateNow1 laterDate:_date1]]) {
        scVo.status = @"-1";
    }
    else {
        scVo.status = @"1";
    }
    
    [sDao saveScheduleDictionary:scVo];
    
    [self refreshSchedule];
    
    return YES;
}


#pragma mark - Private
- (void)initView {
    if (!sDao) {
        sDao = [ScheduleDAO shareScheduleDAO];
    }
    if (!sContentArray) {
       sContentArray = [[NSMutableArray alloc] init]; 
    }
    else {
        [sContentArray removeAllObjects];
    }
    sContentArray = [self getCurrentRecordByUserId:userId limit:5];
    
    if (!sContentArray || [sContentArray count] < 1) {
        [tbSchedule setHidden:YES];
        [timeLineView setHidden:YES];
        [nodataView setHidden:NO];
        
    }
    else {
        [tbSchedule setHidden:NO];
        [timeLineView setHidden:NO];
        [nodataView setHidden:YES];
    }
}

- (NSMutableArray*)getCurrentRecordByUserId:(NSString*)uId limit:(int)lRow {
    NSMutableArray *scheduleData = [sDao getUserSchedule:uId];
    
    
    NSArray *sortedArr = [scheduleData sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSDate *date1 = getDateFromString(@"MM月dd", [obj1 objectForKey: @"dateString"]);
        NSDate *date2 = getDateFromString(@"MM月dd", [obj2 objectForKey: @"dateString"]);
        
        if ([date1 isEqualToDate:date2]) {
            NSDate * date3 = getDateFromString(@"HH:mm", [obj1 objectForKey: @"timeString"]);
            NSDate * date4 = getDateFromString(@"HH:mm", [obj2 objectForKey: @"timeString"]);
            if ([date3 isEqualToDate:[date3 laterDate:date4]]) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            if ([date4 isEqualToDate:[date3 laterDate:date4]]) {
                return (NSComparisonResult)NSOrderedAscending;
            }
        }
        
        if ([date1 isEqualToDate:[date1 laterDate:date2]]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        if ([date2 isEqualToDate:[date1 laterDate:date2]]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    NSMutableArray *arrLimitted = [[NSMutableArray alloc] init];
    if ([sortedArr count] > lRow) {
        arrLimitted = [[NSMutableArray alloc] initWithArray:[sortedArr subarrayWithRange:NSMakeRange(0, lRow)]];
    }
    else {
        arrLimitted = [[NSMutableArray alloc] initWithArray:sortedArr];
    }
    
    NSMutableArray *contentArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < [arrLimitted count]; i++) {
        NSDictionary *dict = [arrLimitted objectAtIndex:i];
        ScheduleContentVo *cVo = [[ScheduleContentVo alloc] init];
        [cVo dictionaryToScheduleContentVO:dict];
        if (cVo) {
            [contentArr addObject:cVo];
        }
    }
    return contentArr;
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [sContentArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"SimpleSchedule";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell){
        cell = [[[NSBundle mainBundle] loadNibNamed:@"SimpleScheduleCell" owner:self options:nil] objectAtIndex:0];
    }
    
    if([cell respondsToSelector:@selector(setCellDataInfo:)]){
        ScheduleContentVo *scVo = [sContentArray objectAtIndex:indexPath.row];
        [cell performSelector:@selector(setCellDataInfo:) withObject:scVo];
    }
    
    [cell setTag:indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!sampleCell) {
        sampleCell = [[[NSBundle mainBundle] loadNibNamed:@"SimpleScheduleCell" owner:self options:nil] objectAtIndex:0];
    }
    return [sampleCell getContentHeight:[sContentArray objectAtIndex:indexPath.row]];
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSLog(@"delete function.....");
//        [dataArray removeObjectAtIndex:indexPath.row];
//        // Delete the row from the data source.
//        [testTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
//        
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

@end
